import os
from .timetool import *
from loguru import logger
from typing import Callable
from fastapi.routing import APIRoute
from starlette.requests import Request
from starlette.responses import Response


def project_path():
    return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


# 定位到log日志文件
log_path = os.path.join(project_path(), 'log')


def make_log():
    if not os.path.exists(log_path):
        os.mkdir(log_path)
        return make_log()
    else:
        return


def create_log_path(log_time):
    make_log()
    log_path_all = os.path.join(log_path, f'{log_time}', 'log.log')
    log_path_info = os.path.join(log_path, f'{log_time}', 'info.log')
    log_path_error = os.path.join(log_path, f'{log_time}', 'error.log')
    logger.add(log_path_all, rotation="12:00", retention="5 days", enqueue=True)
    logger.add(log_path_info, rotation="12:00", retention="5 days", enqueue=True, level='INFO')  # 日志等级分割
    logger.add(log_path_error, rotation="12:00", retention="5 days", enqueue=True, level='ERROR')  # 日志等级分割


async def witer_log(text_log):
    log_path_all = os.path.join(log_path, f'{current_date()}', 'log.log')
    with open(log_path_all, 'a') as logs:
        logs.writelines(text_log)


async def witer_debug_request(request):
    try:
        log_data = await request.json()
    except:
        log_data = '{' + f'{str(request.url.query).replace("=", ":").replace("&", ",")}' + '}'
    text_log = f"""{current_date(True)} | {request.method} | [{request.client.host}] [{request.url.path}] | [{log_data}]\n"""
    await witer_log(text_log)
